//
//  XMLComposeTextView.swift
//  Weibo
//
//  Created by mac on 16/5/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//  实现看到xib效果
@IBDesignable

class XMLComposeTextView: UITextView {
    
    private lazy var placeHolderLable :UILabel = {
    
        let lable = UILabel()
        lable.text = "夏天来了"
        lable.textColor = UIColor.darkGrayColor()
        lable.numberOfLines = 0
        lable.font = UIFont.systemFontOfSize(15)

        return lable
    }()
    //  设置占位文字 ,让属性在xib中显示，加上@IBInspectable
    @IBInspectable var placeHolder :String? {
    
        didSet {
        
            placeHolderLable.text = placeHolder
        }
    }
    
    override var font :UIFont? {
    
        didSet {
        
            if font == nil {
            
                return
            }
            placeHolderLable.font = font
        }
    }
    override var text :String? {
    
        didSet {
        
            placeHolderLable.hidden = hasText()
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
    
//        backgroundColor = UIColor.orangeColor()
        
        addSubview(placeHolderLable)
        
        placeHolderLable.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHolderLable, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        placeHolderLable.frame.origin.x = 5
        placeHolderLable.frame.origin.y = 6
        
    }
    
    @objc func textChange() {
    
        placeHolderLable.hidden = hasText()
    }
    
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
